$(document).ready(function(){
		var tab_counter = 2;
                var $tab_title_input;
		var $tab_content_input;
                var stop = false;
                var paths = new Array();
                var $tabs = $( "#tabs").tabs({
			tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
			add: function( event, ui ) {
				var tab_content = $tab_content_input || "Tab " + tab_counter + " content.";
				$( ui.panel ).append( "<p>" + tab_content + "</p>" );
			}
		});
                //addTab();
                function addTab() {
			var tab_title = $tab_title_input || "Tab " + tab_counter;
			$tabs.tabs( "add", "#tabs-" + tab_counter, tab_title );
                        $tabs.tabs( "option", "selected", "#tabs-" + tab_counter);
			tab_counter++;
		}
                function inArray(needle, haystack) {
                    var length = haystack.length;
                    for(var i = 0; i < length; i++) {
                        if(haystack[i] == needle) {
                            return i;
                        }
                    }
                    return false;
                }

                $( "#tabs span.ui-icon-close" ).live( "click", function() {
                                        var index = $( "li", $tabs ).index( $( this ).parent() );
                                        $tabs.tabs( "remove", index );
                                        //paths[index] = null;
                                        //console.debug($(this).attr("href"));
                                        console.debug(paths[index+1]);
                });
                
                $('body').layout({ 
                    //applyDefaultStyles: true,
                     east__onresize: function () {
                        accordion.accordion('resize')
                    },
                    north__showOverflowOnHover: true
                });
                $('div.ui-layout-west').layout({
				minSize:                        50	// ALL panes
			,	center__paneSelector:	".west-center"
			,	south__paneSelector:	".west-south"
			,	south__size:			300
                 });
                 // first example
                $(".menu").click(function() {
                    $.ajax({
                          type: 'POST',
                          url: (this).attr("path"),
                          success: function(data) {
                              $('#dialog').dialog();
                          }
                    });
                    return false;
                });
                $.ajaxSetup({
                     beforeSend: function() {
                        $('#general-ajax-load').fadeIn();
                     },
                     complete: function() {
                        $('#general-ajax-load').fadeOut();
                     },
                     success: function() {
                        $('#general-ajax-load').fadeOut();
                     }
                });
                $.ajax({
                      type: 'POST',
                      url: '/zfarm/zfarm/index/extensions',
                      success: function(data) {
                      $(".ui-layout-east .ui-layout-content").html(data);
                      //accordion
                      $( "#accordion h3" ).click(function( event ) {
			if ( stop ) {
				event.stopImmediatePropagation();
				event.preventDefault();
				stop = false;
			}
                        });
                        
                        var accordion = $( "#accordion" )
                                .accordion({
                                        fillSpace:	true,
                                        header: "> div > h3"

                                })
                                .sortable({
                                        axis: "y",
                                        handle: "h3",
                                        stop: function() {
                                                stop = true;
                                        }
                        });
                  }
                  });
                      
                $.ajax({
                      type: 'POST',
                      url: '/zfarm/zfarm/index/fileexplorer',
                      success: function(data) {
                          $(".ui-layout-content #browser").html(data);
                          $(".ui-layout-content #browser").treeview();
                          $("span.file").click(function() {
                          var fname = $(this).text();
                          var path = $(this).attr("path");
                          
                          var tabKey = inArray(path, paths);
                          if(tabKey == false){
                          $.ajax({
                          type: 'POST',
                              url: '/zfarm/zfarm/index/codenavigator',
                              data: "file="+$(this).attr("path"),
                              success: function(data) {
                                $(".west-south").html(data);    
                              }
                          });
                          $.ajax({
                              type: 'POST',
                              url: '/zfarm/zfarm/index/loadpage',
                              data: "file="+$(this).attr("path")+"&txid="+tab_counter,
                              success: function(data) {
                              console.debug(inArray(path, paths));
                              // $(".ui-layout-center").html('<ul><li><A href="#tab_1"><SPAN>Tab 1</SPAN></A></li><ul>');
                              // $(".ui-layout-center").tabs();
                              
                                  function extension(fname) {
                                      var pos = fname.lastIndexOf(".");
                                      var strlen = fname.length;
                                      if (pos != -1 && strlen != pos + 1) {
                                        var ext = fname.split(".");
                                        var len = ext.length;
                                        var extension = ext[len - 1].toLowerCase();
                                      } else {
                                        extension = "";
                                      }
                                      return extension;
                                    }

                                  switch (extension(fname)) {
                                        case 'css':
                                            var language = "text/css";
                                            break;
                                        case 'js':
                                            var language = "text/javascript";
                                            break;
                                        default:
                                            var language = "application/x-httpd-php";
                                            break;
                                    }
                                    //$(".ui-layout-center").html(data);
                                    $tab_content_input = data;
                                    $tab_title_input = fname;
                                    paths[tab_counter] = path;
                                    addTab();
                                   var myCodeMirror = CodeMirror.fromTextArea(
                                     document.getElementById("myTextArea-"+(tab_counter-1)),{
                                        lineNumbers: true,
                                        matchBrackets: true,
                                        mode: language,
                                        indentUnit: 4,
                                        indentWithTabs: true,
                                        enterMode: "keep",
                                        tabMode: "shift",
                                        theme: 'eclipse',

                                        onGutterClick: function(cm, n) {
                                          var info = cm.lineInfo(n);
                                          if (info.markerText)
                                            cm.clearMarker(n);
                                          else
                                            cm.setMarker(n, "<span style=\"color: #900\">?</span> %N%");
                                        },
                                        onCursorActivity: function() {
                                            myCodeMirror.setLineClass(hlLine, null);
                                            hlLine = myCodeMirror.setLineClass(myCodeMirror.getCursor().line, "activeline");
                                        }
                                    });
                                    var hlLine = myCodeMirror.setLineClass(0, "activeline");
                                
                                $('#selectThemes').change(function() {
                                    $("#selectThemes option:selected").each(function () {
                                        var theme = $(this).text();
                                        myCodeMirror.setOption("theme", theme);
                                    })
                                });
                                $('#codeSave').click(function(){
                                    myCodeMirror.save();
                                    $.ajax({
                                          type: 'POST',
                                          url: '/zfarm/zfarm/index/savefile',
                                          data: "content="+$("#myTextArea"+(tab_counter-1)).val()+"&path="+$('#filepath').text(),
                                          success: function(data) {
                                              //$('#dialog').dialog();
                                          }
                                    });
                                });
                              }
                           });
                          return false;
                          }else{
                                $tabs.tabs( "option", "selected", "#tabs-" + tabKey);
                          }
                       });
                      }
                });
        });